class ProductsController < ApplicationController
  # GET /articles
  # GET /articles.json
  def index
    #delegates to list method and template
    list
    render("list")
  end

  def list
    @products = Product.all
  end

  def show
    @product = Product.find(params[:id])
  end

  # GET /products/1/edit
  def edit
    @product = Product.find(params[:id])
  end
  
  # GET /products/1/edit
  def new
    @product = Product.new
  end

  #Have to do this song and dance to convert what we read from the form (decimals)
  #to what Money expects (Integers)
  def set_money(product, product_atts)
    product.attributes= product_atts
    product.price = Money.new_with_dollars(Float(product_atts[:price]))
    product.sale_price = Money.new_with_dollars(Float(product_atts[:sale_price]))
    product.actual_price = Money.new_with_dollars(Float(product_atts[:actual_price]))
  end

  # PUT /products/1
  # PUT /products/1.json
  def update
    @product = Product.find(params[:id])
    product_atts = params[:product]

    #Have to do this song and dance to convert what we read from the form (decimals)
    #to what Money expects (Integers)
    set_money(@product, product_atts)

    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product was successfully updated.' }
        format.json { head :ok }
      else
        format.html { render action: "edit" }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

  # POST /products
  # POST /products.json
  def create
    @product = Product.new(params[:product])
    set_money @product, params[:product]

    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product was successfully created.' }
        format.json { render json: @product, status: :created, location: @product }
      else
        format.html { render action: "new" }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end
  
  # DELETE /products/1
  # DELETE /products/1.json
  def destroy
    @product = Product.find(params[:id])
    @product.destroy

    respond_to do |format|
      format.html { redirect_to products_url }
      format.json { head :ok }
    end
  end

end
